// 增强的存档系统
class SaveSystem {
    constructor() {
        this.storageKey = 'zombieSchoolGameSave';
        this.version = '2.0';
        this.autoSaveInterval = 30000; // 30秒自动存档
        this.autoSaveTimer = null;
        this.startAutoSave();
    }
    
    // 开始自动存档
    startAutoSave() {
        this.autoSaveTimer = setInterval(() => {
            try {
                if (window.gameManager && window.gameManager.levelManager && window.gameManager.levelManager.isLevelActive) {
                    this.quickSave();
                }
            } catch (error) {
                console.error('自动存档失败:', error);
                // 不要让自动存档错误影响游戏运行
            }
        }, this.autoSaveInterval);
    }
    
    // 停止自动存档
    stopAutoSave() {
        if (this.autoSaveTimer) {
            clearInterval(this.autoSaveTimer);
            this.autoSaveTimer = null;
        }
    }
    
    // 创建完整存档
    createSaveData() {
        const gameManager = window.gameManager;
        const levelManager = gameManager ? gameManager.levelManager : null;
        const player = window.player;
        
        return {
            version: this.version,
            timestamp: Date.now(),
            player: {
                health: player ? player.health : 100,
                maxHealth: player ? player.maxHealth : 100,
                currentWeapon: player && player.currentWeapon ? {
                    type: player.currentWeapon.type,
                    currentAmmo: player.currentWeapon.currentAmmo,
                    totalAmmo: player.currentWeapon.totalAmmo
                } : null,
                position: player ? { x: player.x, y: player.y } : null,
                shield: player ? player.shield : 0,
                explosiveAmmo: player ? player.explosiveAmmo : 0,
                activeEffects: player ? player.activeEffects : {}
            },
            game: {
                currentLevel: levelManager ? levelManager.currentLevel : 1,
                score: gameManager ? gameManager.score : 0,
                levelScore: gameManager ? gameManager.levelScore : 0,
                lives: gameManager ? gameManager.lives : 3,
                gameStartTime: gameManager ? gameManager.gameStartTime : Date.now(),
                isLevelActive: levelManager ? levelManager.isLevelActive : false,
                levelStartTime: levelManager ? levelManager.levelStartTime : Date.now()
            },
            progress: {
                levelsCompleted: this.getCompletedLevels(),
                levelBestScores: this.getLevelBestScores(),
                totalPlayTime: this.getTotalPlayTime(),
                totalKills: this.getTotalKills(),
                bestWeapons: this.getBestWeapons(),
                achievements: this.getAchievements()
            },
            statistics: {
                gamesPlayed: this.getGamesPlayed(),
                totalScore: this.getTotalScore(),
                averageScore: this.getAverageScore(),
                favoriteLevel: this.getFavoriteLevel(),
                survivalTime: this.getSurvivalTime()
            }
        };
    }
    
    // 保存游戏
    saveGame(saveSlot = 'main') {
        try {
            const saveData = this.createSaveData();
            const saveKey = `${this.storageKey}_${saveSlot}`;
            
            localStorage.setItem(saveKey, JSON.stringify(saveData));
            
            // 更新存档列表
            this.updateSaveList(saveSlot, saveData);
            
            console.log(`游戏已保存到存档槽: ${saveSlot}`);
            this.showSaveNotification('游戏已保存');
            
            return true;
        } catch (error) {
            console.error('保存游戏失败:', error);
            this.showSaveNotification('保存失败', true);
            return false;
        }
    }
    
    // 快速保存
    quickSave() {
        return this.saveGame('quick');
    }
    
    // 加载游戏
    loadGame(saveSlot = 'main') {
        try {
            const saveKey = `${this.storageKey}_${saveSlot}`;
            const savedData = localStorage.getItem(saveKey);
            
            if (!savedData) {
                console.log('没有找到存档');
                return null;
            }
            
            const saveData = JSON.parse(savedData);
            
            // 版本兼容性检查
            if (saveData.version !== this.version) {
                console.log('存档版本不匹配，尝试迁移...');
                return this.migrateSaveData(saveData);
            }
            
            return saveData;
        } catch (error) {
            console.error('加载游戏失败:', error);
            return null;
        }
    }
    
    // 应用存档数据
    applySaveData(saveData) {
        if (!saveData) return false;
        
        try {
            // 恢复游戏管理器状态
            if (window.gameManager) {
                window.gameManager.score = saveData.game.score || 0;
                window.gameManager.levelScore = saveData.game.levelScore || 0;
                window.gameManager.lives = saveData.game.lives || 3;
                window.gameManager.gameStartTime = saveData.game.gameStartTime || Date.now();
                
                // 恢复关卡状态
                if (window.gameManager.levelManager) {
                    window.gameManager.levelManager.currentLevel = saveData.game.currentLevel || 1;
                    window.gameManager.levelManager.isLevelActive = saveData.game.isLevelActive || false;
                    window.gameManager.levelManager.levelStartTime = saveData.game.levelStartTime || Date.now();
                }
            }
            
            // 恢复玩家状态
            if (window.player && saveData.player) {
                window.player.health = saveData.player.health || 100;
                window.player.maxHealth = saveData.player.maxHealth || 100;
                window.player.shield = saveData.player.shield || 0;
                window.player.explosiveAmmo = saveData.player.explosiveAmmo || 0;
                window.player.activeEffects = saveData.player.activeEffects || {};
                
                // 恢复位置
                if (saveData.player.position) {
                    window.player.x = saveData.player.position.x;
                    window.player.y = saveData.player.position.y;
                }
                
                // 恢复武器
                if (saveData.player.currentWeapon) {
                    const weaponData = saveData.player.currentWeapon;
                    window.player.currentWeapon = new Weapon(
                        weaponData.type,
                        weaponData.currentAmmo,
                        weaponData.totalAmmo,
                        0, 0
                    );
                }
                
                // 更新UI
                window.player.updateHealthUI();
                window.player.updateWeaponUI();
            }
            
            // 更新游戏UI
            if (window.gameManager) {
                window.gameManager.updateScoreUI();
            }
            
            console.log('存档数据已应用');
            this.showSaveNotification('游戏已加载');
            return true;
        } catch (error) {
            console.error('应用存档数据失败:', error);
            return false;
        }
    }
    
    // 获取存档列表
    getSaveList() {
        try {
            const saveListKey = `${this.storageKey}_list`;
            const saveList = localStorage.getItem(saveListKey);
            return saveList ? JSON.parse(saveList) : {};
        } catch (error) {
            console.error('获取存档列表失败:', error);
            return {};
        }
    }
    
    // 更新存档列表
    updateSaveList(saveSlot, saveData) {
        try {
            const saveList = this.getSaveList();
            saveList[saveSlot] = {
                timestamp: saveData.timestamp,
                level: saveData.game.currentLevel,
                score: saveData.game.score,
                health: saveData.player.health,
                description: this.generateSaveDescription(saveData)
            };
            
            const saveListKey = `${this.storageKey}_list`;
            localStorage.setItem(saveListKey, JSON.stringify(saveList));
        } catch (error) {
            console.error('更新存档列表失败:', error);
        }
    }
    
    // 生成存档描述
    generateSaveDescription(saveData) {
        const level = saveData.game.currentLevel;
        const score = saveData.game.score;
        const health = saveData.player.health;
        const date = new Date(saveData.timestamp).toLocaleString();
        
        return `第${level}关 - 分数:${score} - 血量:${health} - ${date}`;
    }
    
    // 删除存档
    deleteSave(saveSlot) {
        try {
            const saveKey = `${this.storageKey}_${saveSlot}`;
            localStorage.removeItem(saveKey);
            
            // 从存档列表中移除
            const saveList = this.getSaveList();
            delete saveList[saveSlot];
            
            const saveListKey = `${this.storageKey}_list`;
            localStorage.setItem(saveListKey, JSON.stringify(saveList));
            
            console.log(`存档 ${saveSlot} 已删除`);
            this.showSaveNotification('存档已删除');
            return true;
        } catch (error) {
            console.error('删除存档失败:', error);
            return false;
        }
    }
    
    // 获取已完成的关卡
    getCompletedLevels() {
        const storageManager = window.storageManager;
        if (storageManager) {
            const data = storageManager.loadData();
            return data.progress.levelsCompleted || [];
        }
        
        // 回退机制：从localStorage直接读取
        const completedKey = `${this.storageKey}_completed_levels`;
        const completed = localStorage.getItem(completedKey);
        return completed ? JSON.parse(completed) : [];
    }
    
    // 保存已完成的关卡
    saveCompletedLevel(level) {
        const completedKey = `${this.storageKey}_completed_levels`;
        const completed = this.getCompletedLevels();
        
        if (!completed.includes(level)) {
            completed.push(level);
            localStorage.setItem(completedKey, JSON.stringify(completed));
        }
    }
    
    // 获取关卡最佳分数
    getLevelBestScores() {
        const completed = this.getCompletedLevels();
        const bestScores = {};
        
        // 从localStorage获取每关最佳分数
        for (let level = 1; level <= 10; level++) {
            const scoreKey = `${this.storageKey}_level_${level}_best`;
            const bestScore = localStorage.getItem(scoreKey);
            if (bestScore) {
                bestScores[level] = parseInt(bestScore);
            }
        }
        
        return bestScores;
    }
    
    // 保存关卡最佳分数
    saveLevelBestScore(level, score) {
        const scoreKey = `${this.storageKey}_level_${level}_best`;
        const currentBest = localStorage.getItem(scoreKey);
        
        if (!currentBest || score > parseInt(currentBest)) {
            localStorage.setItem(scoreKey, score.toString());
            this.showSaveNotification(`新纪录！第${level}关最佳分数: ${score}`);
            return true;
        }
        
        return false;
    }
    
    // 获取统计数据
    getTotalPlayTime() {
        const key = `${this.storageKey}_total_playtime`;
        return parseInt(localStorage.getItem(key)) || 0;
    }
    
    getTotalKills() {
        const storageManager = window.storageManager;
        if (storageManager) {
            const data = storageManager.loadData();
            return data.player.totalKills || 0;
        }
        return 0;
    }
    
    getBestWeapons() {
        const storageManager = window.storageManager;
        if (storageManager) {
            const data = storageManager.loadData();
            return data.statistics.weaponsUsed || {};
        }
        return {};
    }
    
    getAchievements() {
        const storageManager = window.storageManager;
        if (storageManager) {
            const data = storageManager.loadData();
            return data.achievements || {};
        }
        return {};
    }
    
    getGamesPlayed() {
        const storageManager = window.storageManager;
        if (storageManager) {
            const data = storageManager.loadData();
            return data.player.gamesPlayed || 0;
        }
        return 0;
    }
    
    getTotalScore() {
        const storageManager = window.storageManager;
        if (storageManager) {
            const data = storageManager.loadData();
            return data.player.totalScore || 0;
        }
        return 0;
    }
    
    getAverageScore() {
        const total = this.getTotalScore();
        const games = this.getGamesPlayed();
        return games > 0 ? Math.floor(total / games) : 0;
    }
    
    getFavoriteLevel() {
        // 基于完成次数确定最喜欢的关卡
        const completed = this.getCompletedLevels();
        const levelCounts = {};
        
        completed.forEach(level => {
            levelCounts[level] = (levelCounts[level] || 0) + 1;
        });
        
        let favorite = 1;
        let maxCount = 0;
        for (const [level, count] of Object.entries(levelCounts)) {
            if (count > maxCount) {
                maxCount = count;
                favorite = parseInt(level);
            }
        }
        
        return favorite;
    }
    
    getSurvivalTime() {
        const key = `${this.storageKey}_survival_time`;
        return parseInt(localStorage.getItem(key)) || 0;
    }
    
    // 数据迁移
    migrateSaveData(oldData) {
        console.log('迁移存档数据...');
        // 这里可以添加版本迁移逻辑
        return null;
    }
    
    // 显示保存通知
    showSaveNotification(message, isError = false) {
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            top: 80px;
            right: 20px;
            background: ${isError ? '#ff4444' : '#44ff44'};
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            z-index: 1000;
            font-family: monospace;
            animation: slideInRight 0.3s ease-out;
        `;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.style.animation = 'slideOutRight 0.3s ease-in';
            setTimeout(() => {
                if (document.body.contains(notification)) {
                    document.body.removeChild(notification);
                }
            }, 300);
        }, 2000);
    }
    
    // 导出存档
    exportSave(saveSlot = 'main') {
        const saveData = this.loadGame(saveSlot);
        if (!saveData) {
            this.showSaveNotification('没有找到存档', true);
            return;
        }
        
        const dataStr = JSON.stringify(saveData, null, 2);
        const dataBlob = new Blob([dataStr], { type: 'application/json' });
        
        const link = document.createElement('a');
        link.href = URL.createObjectURL(dataBlob);
        link.download = `zombie_game_save_${saveSlot}_${new Date().toISOString().split('T')[0]}.json`;
        link.click();
        
        this.showSaveNotification('存档已导出');
    }
    
    // 导入存档
    importSave(file, saveSlot = 'main') {
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const saveData = JSON.parse(e.target.result);
                
                const saveKey = `${this.storageKey}_${saveSlot}`;
                localStorage.setItem(saveKey, JSON.stringify(saveData));
                this.updateSaveList(saveSlot, saveData);
                
                this.showSaveNotification('存档已导入');
            } catch (error) {
                this.showSaveNotification('导入失败：文件格式错误', true);
            }
        };
        reader.readAsText(file);
    }
}

// 添加滑入滑出动画
const saveSystemStyles = document.createElement('style');
saveSystemStyles.textContent = `
    @keyframes slideInRight {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    
    @keyframes slideOutRight {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }
`;
document.head.appendChild(saveSystemStyles);